#include "session_manager.h"
#include "../inc/logger.h"

SessionManager::SessionManager()
{
	for (unsigned short i = 1; i < 65535; i++)
		queAddress.push(i);
	count = 0;
}

SessionManager::~SessionManager()
{
}

void SessionManager::addSession(SessionPtr conn)
{
	cout << std::this_thread::get_id() << endl;
	std::unique_lock<std::mutex> lock(mMutexService);
	AppAddress addr;
	addr.Broker.Id = brokerId;
	if (queAddress.size() == 0)
	{
		LOG4_ERROR("Address space is full!");
		return;
	}
	addr.AddressNo = queAddress.front();
	queAddress.pop();
	conn->setAddress(addr);
	mMapConn[addr] = conn;
	count++;
}

void SessionManager::removeSession(AppAddress addr)
{
	std::unique_lock<std::mutex> lock(mMutexService);
	std::unordered_map<AppAddress, SessionPtr, AppAddressHash>::iterator it = mMapConn.find(addr);
	if (it != mMapConn.end())
	{
		mMapConn.erase(it);
		queAddress.push(addr.AddressNo);
	}
	count--;
}

SessionPtr SessionManager::getSession(AppAddress addr)
{
	std::unique_lock<std::mutex> lock(mMutexService);
	SessionPtr conn = nullptr;
	std::unordered_map<AppAddress, SessionPtr, AppAddressHash>::iterator it = mMapConn.find(addr);
	if (it != mMapConn.end())
		conn = it->second;
	return conn;
}

void SessionManager::clearAll()
{
	std::unique_lock<std::mutex> lock(mMutexService);
	std::unordered_map<AppAddress, SessionPtr, AppAddressHash>::iterator it = mMapConn.begin();
	while (it != mMapConn.end())
	{
		queAddress.push(it->first.AddressNo);
		it++;
	}
	mMapConn.clear();
	count = 0;
}